/*
 * @Author: doing
 * @Date: 2023-08-09 21:04:24
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-08-10 12:35:32
 * @FilePath: \线狮少年\src\store\index.js
 * @Description: 
 * 模块化状态管理器
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
 */
import { createStore, createLogger } from 'vuex';
import menus from './modules/menus.js';
import roles from './modules/roles.js';
import users from './modules/users.js';

import { login, getinfo } from '~/api/manager'
import {
    setToken,
    removeToken
} from '~/composables/auth'


//创建全局变量(之后可以从接口获取用户相关的数据)
const userMes = {
    id: 3,
    username: "admin",
    avatar: "http://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com/public/62af03d1b2aeb.jpg",
    super: 1,
    role: {
        id: 2,
        name: "超级管理员"
    },

}

const state = () => ({
    name: '我是主模块',
    // 用户信息
    userList: {},

    // 侧边宽度
    asideWidth: "250px",

    menuList: [],
    ruleNames: []
})
const getters = {
    text: (state, getters, rootState) => {

    }
}
const mutations = {
    // 记录用户信息
    SET_USERINFO(state, userList) {
        state.userList = userList
    },
    // 展开/缩起侧边
    handleAsideWidth(state) {
        state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
    },
    SET_MENUS(state, menuList) {
        state.menuList = menuList
    },
    SET_RULENAMES(state, ruleNames) {
        state.ruleNames = ruleNames
    }
}

const actions = {
    // 登录
    login({ commit }, { username, password }) {
        return new Promise((resolve, reject) => {
            login(username, password).then(res => {
                setToken(res.token)

                resolve(res)
            }).catch(err => reject(err))
        })
    },
    // 获取当前登录用户信息
    getinfo({ commit }) {
        return new Promise((resolve, reject) => {
            getinfo().then(res => {
                //造假数据,因为接口用的是菜单管理的接口
                res = {...userMes,...res.data.data}
                console.log(res)
                // commit("SET_USERINFO", res) 获取用户信息用于修改操作,之后提供不同的api获取
                commit("SET_MENUS", res.menuTreeList)
                commit("SET_RULENAMES", res.buttonList)
                resolve(res)
            }).catch(err => reject(err))
        })
    },
    // 退出登录
    logout({ commit }) {
        // 移除cookie里的token
        removeToken()
        // 清除当前用户状态 vuex
        commit("SET_USERINFO", {})
    }
}


const debug = process.env.NODE_ENV !== 'production';

export default createStore({
    state,
    getters,
    mutations,
    actions,

    modules: {
        menus,
        roles,
        users
    },
    strict: debug,
    plugins: debug ? [createLogger()] : []
})